//
//  ZCViewController.m
//  MultipeerConnectivity_Demo
//
//  Created by ZhangCheng on 14-5-31.
//  Copyright (c) 2014年 张诚. All rights reserved.
//

#import "ZCViewController.h"

@interface ZCViewController ()

@end

@implementation ZCViewController
static NSString*const xxServiceType=@"xx-service";

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.dataArray=[NSMutableArray arrayWithCapacity:0];
    [self createID];
    
    [self createButton];
    _textView=[[UITextView alloc]initWithFrame:CGRectMake(0, 200, 320, 260)];
    _textView.backgroundColor=[UIColor blackColor ];
    _textView.textColor=[UIColor whiteColor];
    [self.view addSubview:_textView];
    [_textView release];
    
}
-(void)createButton{
    UIButton*button=[UIButton buttonWithType:UIButtonTypeContactAdd];
    button.frame=CGRectMake(100, 100, 100, 100);
    [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    

}
//发送消息
-(void)buttonClick{
//第一种发送消息
    MCSession*session=[self.dataArray firstObject];
    NSString*message=@"hello world";
    NSData*data=[message dataUsingEncoding:NSUTF8StringEncoding];

    NSError*error;
   BOOL is= [session sendData:data toPeers:session.connectedPeers withMode:MCSessionSendDataReliable error:&error];
    if (!is) {
        NSLog(@"error~~%@",error);
    }else{
    
        _textView.text=[NSString stringWithFormat:@"%@\n我说:%@",_textView.text,message];
    }
    
    
//第二种发送资源
    NSString*fileName=@"文件名";
    NSString *filePath = [[NSHomeDirectory() stringByAppendingString:@"/Documents/"] stringByAppendingPathComponent:fileName];
    //对方接收的新文件名
    NSString *modifiedName = [NSString stringWithFormat:@"%@_%@", session.myPeerID.displayName,fileName ];
    NSURL *resourceURL = [NSURL fileURLWithPath:filePath];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSProgress *progress = [session sendResourceAtURL:resourceURL withName:modifiedName toPeer:[[session connectedPeers]firstObject]withCompletionHandler:^(NSError *error) {
            if (error) {
                NSLog(@"Error: %@", [error localizedDescription]);
            }}];
        [progress addObserver:self
                   forKeyPath:@"fractionCompleted"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
        
    });
    
    
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    //进度
  float Value=  [(NSProgress *)object fractionCompleted]*100;
    //更新进度
    //.....
    }
//开始接收一个资源的传递
-(void)session:(MCSession *)session didStartReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID withProgress:(NSProgress *)progress
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [progress addObserver:self
                   forKeyPath:@"fractionCompleted"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    });
}
//接收完成
-(void)session:(MCSession *)session didFinishReceivingResourceWithName:(NSString *)resourceName fromPeer:(MCPeerID *)peerID atURL:(NSURL *)localURL withError:(NSError *)error
{
    //resourceName文件名称
    //localURL 文件打开路径
    

}
-(void)createID{
    //建立一个标示，使用设备名称
   lockPeerID=[[MCPeerID alloc]initWithDisplayName:[[UIDevice currentDevice] name]];
   //开始广播
   _session1 = [[MCSession alloc]initWithPeer:lockPeerID];
    _session1.delegate = self ;
    
    advertiser = [[MCAdvertiserAssistant alloc]initWithServiceType:xxServiceType discoveryInfo:nil session:_session1];
    [advertiser start];
    //开始发现
    MCNearbyServiceBrowser*browser=[[MCNearbyServiceBrowser alloc]initWithPeer:lockPeerID serviceType:xxServiceType];
    browser.delegate=self;
    [browser startBrowsingForPeers];
    
    
}
#pragma mark MCNearbyServiceBrowserDelegate
-(void)browser:(MCNearbyServiceBrowser *)browser lostPeer:(MCPeerID *)peerID
{
    //对方断开连接诶
    NSLog(@"lostPeer~~%@",peerID.displayName);
}
-(void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info
{//收到的是对方的名字
    NSLog(@"foundPeer~%@~~serviceType~%@",peerID.displayName,browser.serviceType);
    //发送端和接收端要保持一致
   static NSString*const xxServiceType=@"xx-service";
     _broswerController = [[MCBrowserViewController alloc]initWithServiceType:xxServiceType session:_session1];
    _broswerController.delegate = self ;
    [self presentViewController:_broswerController animated:YES completion:^{
       // [browser stopBrowsingForPeers];
    }];
    
    
}

#pragma mark MCBrowserViewControllerDelegate
-(void)browserViewControllerWasCancelled:(MCBrowserViewController *)browserViewController
{
    NSLog(@"cancel");
    [_broswerController dismissViewControllerAnimated:YES completion:nil];
}

-(void)browserViewControllerDidFinish:(MCBrowserViewController *)browserViewController
{
    [_broswerController dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"Finish");
}
#pragma mark MCSessionDelegate
//收取消息使用的是session的代理方法
-(void)session:(MCSession *)session didReceiveData:(NSData *)data fromPeer:(MCPeerID *)peerID
{
    NSString*message=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding ];
    NSLog(@"message~~%@",message);
    dispatch_async(dispatch_get_main_queue(), ^{
          _textView.text=[NSString stringWithFormat:@"%@\n%@:说%@",_textView.text,message,peerID.displayName];
    });
}

-(void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state
{
//2为已经连接
    
    NSLog(@"didChangeState\n displayName~%@\n%ld",peerID.displayName,state);
    [self.dataArray addObject:session];
    if (state==2) {
        
       [self dismissViewControllerAnimated:YES completion:^{
           //发送给对方一条消息
           [self buttonClick];
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
